package com.laxia.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Objects;


@Getter
@Setter
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Result<T> implements Serializable {

    public static final int SUCCESS_CODE = 200;
    public static final int DEFAULT_ERROR_CODE = 500;

    private int code;
    private String message;

    @JsonInclude
    @JSONField(serialzeFeatures = SerializerFeature.WriteMapNullValue)
    private T data;

    public static <T> Result<T> success() {
        return new Result<T>().setCode(SUCCESS_CODE).setMessage("success");
    }

    public static <T> Result<T> success(T data) {
        return new Result<T>().setCode(SUCCESS_CODE).setData(data).setMessage("success");
    }

    public static <T> Result<T> error(int code, String msg) {
        return new Result<T>().setCode(code).setMessage(msg);
    }

    public static <T> Result<T> error(String msg) {
        return new Result<T>().setCode(DEFAULT_ERROR_CODE).setMessage(msg);
    }

    public static <T> Result<T> error() {
        return new Result<T>().setCode(DEFAULT_ERROR_CODE).setMessage("系统内部错误");
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isSuccess() {
        return SUCCESS_CODE == code;
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isSuccessAndNotNull() {
        return SUCCESS_CODE == code && Objects.nonNull(data);
    }
}
